#include "app.h"
#include "math.h"

static const char *TAG = "user_app";

extern SemaphoreHandle_t sem_Key_Value;
extern SemaphoreHandle_t sem_Pwm_Change;
extern SemaphoreHandle_t sem_Ble_Get_Data;
extern SemaphoreHandle_t sem_Uart_Get_Data;
extern SemaphoreHandle_t sem_Dis_Change_Flag;

tSys_Status Sys_Status = 
{
    .Argument_Value = 0,
    .Ble_Send_Rate = 50,
    .Pwm_Amp_Num = 90,
    .Mode_Value = 1,
};

tSys_Flag Sys_Flag = 
{
    .System_Power = 0,
    
};


/// @brief 功能函数：清除字符串“s”中的指定字符‘ch’。
/// @param s 目标字符串
/// @param ch   指定字符
void del_chr( char *s, char ch )
{
    char *t=s; //目标指针先指向原串头
    while( *s != '\0' ) //遍历字符串s
    {
        if ( *s != ch ) //如果当前字符不是要删除的，则保存到目标串中
            *t++=*s;
        s++ ; //检查下一个字符
    }
    *t='\0'; //置目标串结束符。
}


/// @brief 微秒级延时函数
/// @param us 
void us_delay(uint32_t us)
{
    uint64_t start_time = esp_timer_get_time();
 
    while ((esp_timer_get_time() - start_time) < us);
}


/**
 * @brief 将ADC采样值转换为温度值
 * @param adc_value ESP32 ADC采样值 (0-4095)
 * @return 温度值 (摄氏度)
 */
int adc_to_temperature(int adc_value) {
    // 电路参数
    const float VCC = 12.0f;          // 电源电压 12V
    const float R2 = 1.0f;            // 采样电阻 1kΩ
    const float R3 = 3.0f;            // 中间电阻 3kΩ
    const float VREF = 3.3f;          // ESP32参考电压 3.3V
    const int ADC_MAX = 4095;         // ESP32 ADC最大值 (12位)
    
    // NTC 10K 3950参数
    const float R0 = 10.0f;           // 额定电阻值 10kΩ @ 25°C
    const float T0 = 298.15f;         // 额定温度 25°C = 298.15K
    const float B_VALUE = 3950.0f;    // B值 3950K
    
    // 1. 计算ADC电压值
    float adc_voltage = (adc_value * VREF) / ADC_MAX;
    
    // 2. 计算电路电流 (忽略ADC输入阻抗影响)
    // 总电阻 = Rt + R3 + R2
    // 电流 I = VCC / (Rt + R3 + R2)
    // 采样电压 V_adc = I * R2 = VCC * R2 / (Rt + R3 + R2)
    // 所以：Rt = (VCC * R2 / adc_voltage) - R3 - R2
    
    float rt = (VCC * R2 / adc_voltage) - R3 - R2;
    
    // 防止计算错误（电压超出范围时rt可能为负值）
    if (rt <= 0) {
        return -273.15f; // 返回绝对零度表示错误
    }
    
    // 3. 使用Steinhart-Hart方程计算温度
    // 1/T = 1/T0 + (1/B) * ln(Rt/R0)
    float ln_r = log(rt / R0);
    float inv_t = (1.0f / T0) + (ln_r / B_VALUE);
    float temp_kelvin = 1.0f / inv_t;
    float temp_celsius = temp_kelvin - 273.15f;
    
    return (int ) (temp_celsius * 10);
}

/// @brief 蓝牙数据接收后的处理逻辑函数
/// @param JSON_Data 接收格式化后的接收数据
void Process_Ble_Data(cJSON* JSON_Data)
{
    cJSON *value = NULL , *ReData = NULL;
    char str[512] = { 0 };
    char *str1 = NULL;

    ReData = cJSON_CreateObject();  // 初始化返回数据结构

    char *str_logo = cJSON_Print(JSON_Data);    // 接收到的字符数据打印
   // ESP_LOGI(TAG, " JSON_Data = %s\n", str_logo);
    cJSON_free(str_logo);

///////////    读取指令   ////////
    value = cJSON_GetObjectItem(JSON_Data, "Orde");
    if (value != NULL)
    {
///////////////////////////////    获取版本号   ///////////////////////////////////////////////////////
        if( strcmp( value->valuestring, "ReadVersion") == 0)
        {
            cJSON_AddNumberToObject(ReData, "Code", 0);

            sprintf( str , "%02X%02X%02X%02X%02X%02X",Sys_Status.Ble_MAC[0],Sys_Status.Ble_MAC[1],Sys_Status.Ble_MAC[2],Sys_Status.Ble_MAC[3],Sys_Status.Ble_MAC[4],Sys_Status.Ble_MAC[5] );
            cJSON_AddStringToObject(ReData, "SNO", str);
            cJSON_AddStringToObject(ReData, "Version", CODE_VERSION);
        }
///////////////////////////////    获取设备信息   ///////////////////////////////////////////////////////
        else if( strcmp( value->valuestring, "ReadStatus") == 0)
        {
            cJSON_AddNumberToObject(ReData, "Code", 0);

            (Sys_Flag.System_Power == 1)? cJSON_AddStringToObject(ReData, "Power", "ON"):cJSON_AddStringToObject(ReData, "Power", "OFF");
            (Sys_Flag.Led_Start_Flag == 1)? cJSON_AddStringToObject(ReData, "Work", "Run"):cJSON_AddStringToObject(ReData, "Work", "Stop");
            cJSON_AddNumberToObject(ReData, "Mode", Sys_Status.Mode_Value);
            cJSON_AddNumberToObject(ReData, "SetTime", Sys_Status.Set_Value);
            cJSON_AddNumberToObject(ReData, "RemTime", Sys_Status.Time_Value );
            cJSON_AddNumberToObject(ReData, "IntenVal", Sys_Status.Streng_Value);
            cJSON_AddNumberToObject(ReData, "HeatVal", Sys_Status.Heat_Value);
            cJSON_AddNumberToObject(ReData, "DataRate", Sys_Status.Ble_Send_Rate);
            cJSON_AddNumberToObject(ReData, "CurrentLev", Sys_Status.Current_Value);

            uint32_t temp = adc_to_temperature( Sys_Status.Temp_Adc_Value  );
            cJSON_AddNumberToObject(ReData, "TempVal", temp);
        }
///////////////////////////////    返回参数错误，命令解析失败   ///////////////////////////////////////////////////////
        else 
        {
            cJSON_AddNumberToObject(ReData, "Code", 2);
            cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
        }
    }

    else 
    {
///////////    设置电源开关指令   ////////
        if ((value = cJSON_GetObjectItem(JSON_Data, "SetPower")) != NULL)
        {
            if (strcmp(value->valuestring, "ON") == 0)
            {
                Power_ON_Process();
                User_Uart_Send_Data("S1");
                ESP_LOGI(TAG, " BLE SET Power ON");
                cJSON_AddNumberToObject(ReData, "Code", 0);
                cJSON_AddStringToObject(ReData, "Content", "OK");
            }
            else if (strcmp(value->valuestring, "OFF") == 0)
            {
                Power_OFF_Process();
                ESP_LOGI(TAG, " BLE SET Power OFF");
                cJSON_AddNumberToObject(ReData, "Code", 0);
                cJSON_AddStringToObject(ReData, "Content", "OK");
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 1);
                cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
            }
        }
///////////    设置开始/暂停指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetWork")) != NULL)
        {
            if (Sys_Flag.System_Power == 1)
            {
                if (strcmp(value->valuestring, "Run") == 0)
                {

                    Sys_Flag.Led_Start_Flag = 1;
                    ESP_LOGI(TAG, " BLE SET Start Work");
                    cJSON_AddNumberToObject(ReData, "OK", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else if (strcmp(value->valuestring, "Stop") == 0)
                {
                    Sys_Flag.Led_Start_Flag = 0;
                    ESP_LOGI(TAG, " BLE SET Stop Work");
                    cJSON_AddNumberToObject(ReData, "OK", 0);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
///////////    设置工作模式指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetMode")) != NULL)
        {
            if (Sys_Flag.System_Power == 1 )
            {
                if(value->valueint <= MODE_NUM_MAX && value->valueint > 0)
                {
                    Sys_Status.Mode_Value = value ->valueint;
                    ESP_LOGI(TAG, " BLE SET Sys_Status.Mode_Value = %d", (int)Sys_Status.Mode_Value);
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON");
            }
        }
///////////    设置工作时间指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetTime")) != NULL)
        {
            if (Sys_Flag.System_Power == 1 )
            {
                if(value->valueint <= 6000 && value->valueint > -1)
                {
                    Sys_Status.Time_Value = value ->valueint;
                    Sys_Status.Set_Value = Sys_Status.Time_Value;
                    ESP_LOGI(TAG, " BLE SET Sys_Status.Time_Value = %d", (int)Sys_Status.Time_Value);
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
///////////    设置工作强度指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetInten")) != NULL)
        {
            if (Sys_Flag.System_Power == 1 )
            {
                if(value->valueint <= 99 && value->valueint > -1)
                {
                    Sys_Status.Streng_Value = value ->valueint;
                    ESP_LOGI(TAG, " BLE SET Sys_Status.Streng_Value = %d", (int)Sys_Status.Streng_Value);
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
///////////    设置加热强度指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetHeat")) != NULL)
        {
            if (Sys_Flag.System_Power == 1)
            {
                if(value->valueint <= 3 && value->valueint > -1)
                {
                    Sys_Status.Heat_Value = value ->valueint;
                    
                    ESP_LOGI(TAG, " BLE SET Sys_Status.Heat_Value = %d", (int)Sys_Status.Heat_Value);
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
///////////    设置连续数据刷新时间指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetDataRate")) != NULL)
        {
            if (Sys_Flag.System_Power == 1 )
            {
                if(value->valueint <= 1000 && value->valueint > 49)
                {
                    Sys_Status.Ble_Send_Rate = value ->valueint;
                    ESP_LOGI(TAG, " BLE SET Sys_Status.Ble_Send_Rate = %d", (int)Sys_Status.Ble_Send_Rate);
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
///////////    设置连续数据开启指令   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SuccessiveData")) != NULL)
        {
            if (Sys_Flag.System_Power == 1 )
            {
                if (strcmp(value->valuestring, "ON") == 0)
                {

                    Sys_Flag.Ble_SetDataRate_Flag = 1;
                    ESP_LOGI(TAG, " BLE SET SuccessiveData ON");
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else if (strcmp(value->valuestring, "OFF") == 0)
                {
                    Sys_Flag.Ble_SetDataRate_Flag = 0;
                    ESP_LOGI(TAG, " BLE SET SuccessiveData OFF");
                    cJSON_AddNumberToObject(ReData, "Code", 0);
                    cJSON_AddStringToObject(ReData, "Content", "OK");
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
            }
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
///////////    设置自定义模式   ////////
        else if ((value = cJSON_GetObjectItem(JSON_Data, "SetCustMode")) != NULL)
        {
            cJSON *cjson_str = NULL;
            int v_adj = 0, fr = 0, tcont = 0, maxcont = 0, amp = 0 , err = 0;
            

            if (Sys_Flag.System_Power == 1)
            {
                if ((cjson_str = cJSON_GetObjectItem(value, "adj_num")) != NULL)
                {
                    v_adj = cjson_str->valueint;
                }
                else err++;

                if ((cjson_str = cJSON_GetObjectItem(value, "frequency")) != NULL && (err ==0))
                {
                    fr = cjson_str->valueint;
                }
                else err++;

                if ((cjson_str = cJSON_GetObjectItem(value, "timer_cont")) != NULL && (err ==0))
                {
                    tcont = cjson_str->valueint;
                }
                else err++;

                if ((cjson_str = cJSON_GetObjectItem(value, "max_cont")) != NULL && (err ==0))
                {
                    maxcont = cjson_str->valueint;
                }
                else err++;

                if ((cjson_str = cJSON_GetObjectItem(value, "amp_num")) != NULL && (err ==0))
                {
                    amp = cjson_str->valueint;
                }
                else err++;
                
                if(err == 0)
                {
                    err = pwm_mode_custom_init(v_adj , fr , tcont , maxcont ,amp);
                   // ESP_LOGI(TAG, " v_adj = %d , fr = %d , tcont = %d , maxcont = %d , amp = %d err = %d", v_adj,fr,tcont,maxcont,amp,err);
                    if(err == 0)
                    {
                        ESP_LOGI(TAG, " BLE SET CustMode OK");
                        Sys_Status.Mode_Value = 10;
                        cJSON_AddNumberToObject(ReData, "Code", 0);
                        cJSON_AddStringToObject(ReData, "Content", "OK");
                    }
                    else
                    {
                        cJSON_AddNumberToObject(ReData, "Code", 4);
                        cJSON_AddStringToObject(ReData, "Content", "VALUE  RANGE ERR");
                    }
                }
                else
                {
                    cJSON_AddNumberToObject(ReData, "Code", 1);
                    cJSON_AddStringToObject(ReData, "Content", "VALUE ERR");
                }
              // cJSON_Delete(cjson_str);
            }   
            else
            {
                cJSON_AddNumberToObject(ReData, "Code", 3);
                cJSON_AddStringToObject(ReData, "Content", "Power is not ON ");
            }
        }
        else
        {
            cJSON_AddNumberToObject(ReData, "Code", 2);
            cJSON_AddStringToObject(ReData, "Content", "CAMD ERR");
        }
    }

    xSemaphoreGive(sem_Pwm_Change);     // 不管有没有变化，都刷新
    xSemaphoreGive(sem_Dis_Change_Flag);    // 不管有没有变化，都刷新

    str1 = cJSON_PrintUnformatted(ReData);

    memcpy( Sys_Status.Ble_SendData_Buff , str1 , strlen(str1 )+ 1 );

    Sys_Flag.Ble_Send_Data_Flag = 1;
    ESP_LOGI("Ble", " Ble_SendData_Buff = %s\n",  Sys_Status.Ble_SendData_Buff);
    //vTaskDelay(2);  // 为解决数据还没发送就被释放问题。
    cJSON_free(str1);
    cJSON_Delete(ReData);
}

void Power_ON_Process(void)
{
    ESP_LOGI(TAG, "Power ON ");
    Sys_Flag.System_Power = 1; // 开机

    Sys_Status.Set_Value = TIME_DEFINE * 60;
    Sys_Status.Mode_Value = MODE_DEFINE;

    Sys_Status.Time_Value = Sys_Status.Set_Value;
    Sys_Status.Streng_Value = 0;
    Sys_Status.Heat_Value = 0;
    Sys_Status.Argument_Value = 0;
    Sys_Flag.Led_Start_Flag = 0;
    Sys_Flag.Led_Heat_Flag = 0;

    
    Sys_Flag.Led_Mode_Num_Flag = 1;
    Sys_Flag.Led_Time_Num_Flag = 1;
    Sys_Flag.Led_Streng_Num_Flag = 1;
    Sys_Flag.Led_Heat_Num_Flag = 1;

    Sys_Flag.Led_Minute_Flag = 1;
    Sys_Status.Led_Flash_Time = 0;

    Sys_Flag.Ble_SetDataRate_Flag = 0;
    
    
    
    xSemaphoreGive(sem_Dis_Change_Flag);
}

void Power_OFF_Process(void)
{
    ESP_LOGI(TAG, "Power OFF ");

    Sys_Flag.System_Power = 0; // 关机

    Sys_Status.Streng_Value = 0;
    Sys_Status.Heat_Value = 0;

    Sys_Flag.Ble_SetDataRate_Flag = 0;

    xSemaphoreGive(sem_Dis_Change_Flag);
    xSemaphoreGive(sem_Pwm_Change);

}

void Work_Start_Process(void)
{
    Sys_Flag.Led_Start_Flag = 1;

    xSemaphoreGive(sem_Dis_Change_Flag);
    xSemaphoreGive(sem_Pwm_Change);
}

void Work_Stop_Process(void)
{
    Sys_Flag.Led_Start_Flag = 0;

    xSemaphoreGive(sem_Dis_Change_Flag);
    xSemaphoreGive(sem_Pwm_Change);
}

void Change_Mode_Process(char mode)
{
    if(mode < 10)
        Sys_Status.Mode_Value = mode;

    xSemaphoreGive(sem_Dis_Change_Flag);
    xSemaphoreGive(sem_Pwm_Change);
}

void Change_TimeAdd_Process(int time)
{
    if (Sys_Flag.System_Power == 1)     //  开机情况下有效
    {
        if (Sys_Status.Time_Value < (100 * 60))
            Sys_Status.Time_Value += (time * 60);
        if (Sys_Status.Time_Value > (100 * 60))
            Sys_Status.Time_Value = (100 * 60);

        Sys_Status.Set_Value = Sys_Status.Time_Value;
        xSemaphoreGive(sem_Dis_Change_Flag);
    }
}

void Change_TimeSub_Process(int time)
{
    if (Sys_Flag.System_Power == 1) //  开机情况下有效
    {
        if (Sys_Status.Time_Value > 0)
            Sys_Status.Time_Value -= (time * 60);
        if (Sys_Status.Time_Value < (5 * 60))
            Sys_Status.Time_Value = (5 * 60);
        Sys_Status.Set_Value = Sys_Status.Time_Value;
        xSemaphoreGive(sem_Dis_Change_Flag);
    }
}

void Change_StrengAdd_Process(int  val)
{
    if (Sys_Flag.System_Power == 1) //  开机情况下有效
    {
        if (Sys_Status.Streng_Value < 99)
            Sys_Status.Streng_Value += val;
        if (Sys_Status.Streng_Value > 99)
            Sys_Status.Streng_Value = 99;
        xSemaphoreGive(sem_Pwm_Change);
        xSemaphoreGive(sem_Dis_Change_Flag);
    }
}

void Change_StrengSub_Process(int  val)
{
    if (Sys_Flag.System_Power == 1) //  开机情况下有效
    {
        if (Sys_Status.Streng_Value > 0)
            Sys_Status.Streng_Value -= val;
        if (Sys_Status.Streng_Value < 0)
            Sys_Status.Streng_Value = 0;
        xSemaphoreGive(sem_Pwm_Change);
        xSemaphoreGive(sem_Dis_Change_Flag);
    }
}

void Hand_key_Gpio_Init( void )
{

    gpio_config_t gpio_cfg =
        {
            .pin_bit_mask = (1ULL << HAND_KEY_ADD) | (1ULL << HAND_KEY_SUB),  // 定义IO口属性
            .pull_down_en = GPIO_PULLDOWN_ENABLE,
            .pull_up_en = GPIO_PULLUP_DISABLE,
            .mode = GPIO_MODE_INPUT,
            .intr_type = GPIO_INTR_DISABLE,
        };

    gpio_config(&gpio_cfg);

}

void Hand_Process_Key(void)
{
    static bool tt = 0 ; // 重复操作标记
    if( HAND_GET_KEY_ADD == 1 )
    {
        if( tt == 0 )
        {
            tt = 1;
            Sys_Status.Key_Vaule = Str_Add_Key;
            Sys_Flag.Key_Sustain_Flag = 0;
            xSemaphoreGive(sem_Key_Value);
        }
    }
    else if( HAND_GET_KEY_SUB == 1)
    {
        if( tt == 0 )
        {
            tt = 1;
            Sys_Status.Key_Vaule = Str_Sub_Key;
            Sys_Flag.Key_Sustain_Flag = 0;
            xSemaphoreGive(sem_Key_Value);
        }
    }
    else if(tt != 0)
    {
        tt = 0;
    }


}

void Change_Heat_Process(int  val) 
{
    if (Sys_Flag.System_Power == 1) //  开机情况下有效
    {
        if( val < 4 && val > 0 )
        {
            Sys_Status.Heat_Value = val;
            Sys_Flag.Led_Heat_Flag = 1;
        }
        else if(val == 0)
        {
            Sys_Status.Heat_Value = 0;
            Sys_Flag.Led_Heat_Flag = 0;
        }
        xSemaphoreGive(sem_Pwm_Change);
        xSemaphoreGive(sem_Dis_Change_Flag);
    }
}

void Process_Key(uint32_t key_value , bool sustain_flag)
{
    if (key_value == Power_Key)
    {
        if (Sys_Flag.System_Power == 0)
        {
            Power_ON_Process();
            User_Uart_Send_Data("S1");
        }
        else
        {
            Power_OFF_Process();
        }
    }
    else if (Sys_Flag.System_Power == 1) // 开机状态下
    {
        switch (key_value)
        {
        case Start_Key:
            ESP_LOGI(TAG, "key_value = Start_Key");
            Sys_Flag.Led_Start_Flag = !Sys_Flag.Led_Start_Flag;

            if (Sys_Status.Led_Flash_Time != 0)
            {
                Sys_Status.Led_Flash_Time = 0;
            }
            break;
        case Heat_Add_Key:
            ESP_LOGI(TAG, "key_value = Heat_Add_Key");
            if (Sys_Status.Heat_Value < 3)
                Sys_Status.Heat_Value++;
            if(Sys_Status.Heat_Value != 0) Sys_Flag.Led_Heat_Flag = 1;
            else Sys_Flag.Led_Heat_Flag = 0;
            break;
        case Heat_Sub_Key:
            ESP_LOGI(TAG, "key_value = Heat_Sub_Key");
            if (Sys_Status.Heat_Value > 0)
                Sys_Status.Heat_Value--;

            if(Sys_Status.Heat_Value != 0) Sys_Flag.Led_Heat_Flag = 1;
            else Sys_Flag.Led_Heat_Flag = 0;
            break;
        case Str_Add_Key:
            ESP_LOGI(TAG, "key_value = Str_Add_Key");
            if (Sys_Status.Streng_Value < 100)
                Sys_Status.Streng_Value++;
            if (Sys_Flag.Key_Sustain_Flag != 0)
                Sys_Flag.Key_Sustain_Flag = 0;
            break;
        case Str_Sub_Key:
            ESP_LOGI(TAG, "key_value = Str_Sub_Key");
            if (Sys_Status.Streng_Value > 0)
                Sys_Status.Streng_Value--;
            if (Sys_Status.Streng_Value < 0)
                Sys_Status.Streng_Value = 0;
            if (Sys_Flag.Key_Sustain_Flag != 0)
                Sys_Flag.Key_Sustain_Flag = 0;
            break;
        case Time_Add_Key:
            ESP_LOGI(TAG, "key_value = Time_Add_Key");
            if (Sys_Status.Time_Value < (100 * 60))
                Sys_Status.Time_Value += (5 * 60);
            if (Sys_Status.Time_Value > (100 * 60))
                Sys_Status.Time_Value = (100 * 60);
            Sys_Status.Set_Value = Sys_Status.Time_Value;
            if (Sys_Flag.Key_Sustain_Flag != 0)
                Sys_Flag.Key_Sustain_Flag = 0;
            break;
        case Time_Sub_Key:
            ESP_LOGI(TAG, "key_value = Time_Sub_Key");
            if (Sys_Status.Time_Value > 0)
                Sys_Status.Time_Value -= (5 * 60);
            if (Sys_Status.Time_Value < (5 * 60))
                Sys_Status.Time_Value = (5 * 60);
            Sys_Status.Set_Value = Sys_Status.Time_Value;
            if (Sys_Flag.Key_Sustain_Flag != 0)
                Sys_Flag.Key_Sustain_Flag = 0;
            break;
        case Mode_Add_Key:
            ESP_LOGI(TAG, "key_value = Mode_Add_Key");
            if (Sys_Status.Mode_Value < MODE_NUM_MAX)
                Sys_Status.Mode_Value++;
            else
            {
                Sys_Status.Mode_Value = 1;
            }
            break;
        case Mode_Sub_Key:
            ESP_LOGI(TAG, "key_value = Mode_Sub_Key");
            if(Sys_Status.Mode_Value > MODE_NUM_MAX)
            {
                Sys_Status.Mode_Value = MODE_NUM_MAX;
            }
            else
            {
                if (Sys_Status.Mode_Value > 1)
                    Sys_Status.Mode_Value--;
                if (Sys_Status.Mode_Value < 1)
                    Sys_Status.Mode_Value = 1;
            }
            
            break;
        }

        xSemaphoreGive(sem_Pwm_Change);
        xSemaphoreGive(sem_Dis_Change_Flag);
        Sys_Status.Led_Flash_Time = TIME_FLASH_DEFINE * 10;
    }
}

void Uart_Process_Data( char * buff )
{
    char *rbuff = malloc(strlen(buff) + 1);
    strcpy(rbuff, buff);
    if (strcmp(rbuff, "ON\r\n") == 0)
    {
        ESP_LOGI(TAG, "get power on code");
        Power_ON_Process();
    }
    else if (strcmp(rbuff, "OFF\r\n") == 0)
    {
        ESP_LOGI(TAG, "get power DOWN code");
        Power_OFF_Process();
    }
    else if (strcmp(rbuff, "START\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "get work start code");
            User_Uart_Send_Data("S17");
            Work_Start_Process();
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "STOP\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "get work stop code");
            User_Uart_Send_Data("S18");
            Work_Stop_Process();
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "M1\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set mode 1 code");
            User_Uart_Send_Data("S5");
            Change_Mode_Process(1);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "M2\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set mode 2 code");
            User_Uart_Send_Data("S6");
            Change_Mode_Process(2);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "M3\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set mode 3 code");
            User_Uart_Send_Data("S7");
            Change_Mode_Process(3);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "M4\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set mode 4 code");
            User_Uart_Send_Data("S8");
            Change_Mode_Process(4);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "M5\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set mode 5 code");
            User_Uart_Send_Data("S9");
            Change_Mode_Process(5);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "T+1\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Time add code");
            User_Uart_Send_Data("S14");
            Change_TimeAdd_Process(5);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "T+10\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Time add code");
            User_Uart_Send_Data("S14");
            Change_TimeAdd_Process(10);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "T-1\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Time sub code");
            User_Uart_Send_Data("S15");
            Change_TimeSub_Process(5);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "T-10\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Time sub code");
            User_Uart_Send_Data("S15");
            Change_TimeSub_Process(10);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "Str+1\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Str add code");
            User_Uart_Send_Data("S14");
            Change_StrengAdd_Process(1);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "Str+2\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Str add code");
            User_Uart_Send_Data("S14");
            Change_StrengAdd_Process(2);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "Str-1\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Str sub code");
            User_Uart_Send_Data("S16");
            Change_StrengSub_Process(1);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "Str-2\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set Str sub code");
            User_Uart_Send_Data("S16");
            Change_StrengSub_Process(2);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "H1\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set heat 1 code");
            if( Sys_Flag.Led_Heat_Flag == 1 )
                User_Uart_Send_Data("S121");
            else
                User_Uart_Send_Data("S19");
            Change_Heat_Process(1);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "H2\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set heat 2 code");
            if( Sys_Flag.Led_Heat_Flag == 1 )
                User_Uart_Send_Data("S121");
            else
                User_Uart_Send_Data("S19");
            Change_Heat_Process(2);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "H3\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set heat 3 code");
            if( Sys_Flag.Led_Heat_Flag == 1 )
                User_Uart_Send_Data("S121");
            else
                User_Uart_Send_Data("S19");
            Change_Heat_Process(3);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "H-ON\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set heat ON code");
            User_Uart_Send_Data("S19");
            Change_Heat_Process(3);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "H-OFF\r\n") == 0)
    {
        if (Sys_Flag.System_Power == 1)
        {
            ESP_LOGI(TAG, "set heat OFF code");
            User_Uart_Send_Data("S120");
            Change_Heat_Process(0);
        }
        else
        {
            User_Uart_Send_Data("S13");
        }
    }
    else if (strcmp(rbuff, "WORK\r\n") == 0)
    {

        ESP_LOGI(TAG, "tw is work");
        Sys_Flag.Led_Wifi_Flag = 1;
        xSemaphoreGive(sem_Dis_Change_Flag);
    }
    else if (strcmp(rbuff, "SLEEP\r\n") == 0)
    {

        ESP_LOGI(TAG, "tw is sleep");
        Sys_Flag.Led_Wifi_Flag = 0;
        xSemaphoreGive(sem_Dis_Change_Flag);
    }

    free(rbuff);
}

void App_Task(void* param)
{

    ESP_LOGI(TAG, "this is app task" );
    vTaskDelay(1000);
    Hand_key_Gpio_Init();
    

    while(1)
    {
        if (xSemaphoreTake(sem_Ble_Get_Data, 1) == pdTRUE) // 不阻塞的信号量获取   // 是否需要处理蓝牙数据
        {
            ESP_LOGI(TAG, " Get Ble Data = %s " , Sys_Status.Ble_Data_Buff);
            cJSON *data = cJSON_Parse(Sys_Status.Ble_Data_Buff);
            if( data != NULL )
                Process_Ble_Data(data);
            else 
                ESP_LOGI(TAG, " Get ERR JSON Data = %s " , Sys_Status.Ble_Data_Buff);
            cJSON_Delete(data);
        }

        if (xSemaphoreTake(sem_Uart_Get_Data, 1) == pdTRUE) // 不阻塞的信号量获取   // 是否需要处理串口数据
        {
            ESP_LOGI(TAG, " Get Uart Data = %s " , Sys_Status.Uart_Data_Buff);
            if(strlen(Sys_Status.Uart_Data_Buff) < UART_LEN_MAX)
            {
                Uart_Process_Data(Sys_Status.Uart_Data_Buff);
            }
            else{
                ESP_LOGI(TAG, " Get ERR Uart Data = %s " , Sys_Status.Uart_Data_Buff);
            }
        }

        if (xSemaphoreTake(sem_Key_Value, 1) == pdTRUE) // 不阻塞的信号量获取   // 是否需要处理按键
        {
           // ESP_LOGI(TAG, " Sys_Status.Key_Vaule = 0x%04x",(int )Sys_Status.Key_Vaule);
            Process_Key(Sys_Status.Key_Vaule, Sys_Flag.Key_Sustain_Flag);
        }
        Hand_Process_Key();   

        //ESP_LOGI(TAG, " Sys_Status.Ble_Data_len = %d",strlen(Sys_Status.Ble_Data_Buff));

        vTaskDelay(10);
    }

}